<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="小程序," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="学习资料小程序LeanCloud文档： https://leancloud.cn/docs/weapp.htmlLeanCloud数据存储JS文档： https://leancloud.cn/docs/leanstorage_guide-js.html 配置环境 下载 av-weapp-min.js，移动到 libs 目录下。 在app.js中初始化  const AV = require(&apos;li">
<meta name="keywords" content="小程序">
<meta property="og:type" content="article">
<meta property="og:title" content="小程序接入LeanCloud学习笔记">
<meta property="og:url" content="http://soaic.github.io/2017/08/18/小程序接入LeanCloud学习笔记/index.html">
<meta property="og:site_name" content="Soaic&#39;s Blog">
<meta property="og:description" content="学习资料小程序LeanCloud文档： https://leancloud.cn/docs/weapp.htmlLeanCloud数据存储JS文档： https://leancloud.cn/docs/leanstorage_guide-js.html 配置环境 下载 av-weapp-min.js，移动到 libs 目录下。 在app.js中初始化  const AV = require(&apos;li">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-08-17T17:13:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="小程序接入LeanCloud学习笔记">
<meta name="twitter:description" content="学习资料小程序LeanCloud文档： https://leancloud.cn/docs/weapp.htmlLeanCloud数据存储JS文档： https://leancloud.cn/docs/leanstorage_guide-js.html 配置环境 下载 av-weapp-min.js，移动到 libs 目录下。 在app.js中初始化  const AV = require(&apos;li">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://soaic.github.io/2017/08/18/小程序接入LeanCloud学习笔记/"/>





  <title>小程序接入LeanCloud学习笔记 | Soaic's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Soaic's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Soaic</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://soaic.github.io/2017/08/18/小程序接入LeanCloud学习笔记/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Soaic">
      <meta itemprop="description" content="Welcome!">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Soaic's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">小程序接入LeanCloud学习笔记</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-18T12:00:00+08:00">
                2017-08-18
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2017/08/18/小程序接入LeanCloud学习笔记/" class="leancloud_visitors" data-flag-title="小程序接入LeanCloud学习笔记">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="学习资料"><a href="#学习资料" class="headerlink" title="学习资料"></a>学习资料</h3><p>小程序LeanCloud文档： <a href="https://leancloud.cn/docs/weapp.html" target="_blank" rel="external">https://leancloud.cn/docs/weapp.html</a><br>LeanCloud数据存储JS文档： <a href="https://leancloud.cn/docs/leanstorage_guide-js.html" target="_blank" rel="external">https://leancloud.cn/docs/leanstorage_guide-js.html</a></p>
<h3 id="配置环境"><a href="#配置环境" class="headerlink" title="配置环境"></a>配置环境</h3><ol>
<li>下载 <a href="https://unpkg.com/leancloud-storage@%5E3.0.0-alpha/dist/av-weapp-min.js" target="_blank" rel="external">av-weapp-min.js</a>，移动到 libs 目录下。</li>
<li>在app.js中初始化</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="keyword">const</span> AV = <span class="built_in">require</span>(<span class="string">'libs/av-weapp-min.js'</span>);</div><div class="line">AV.init(&#123;</div><div class="line">    appId: <span class="string">'nSNhFcJCeysT9vRXgfNvtbQF-gzGzoHsz'</span>,</div><div class="line">    appKey: <span class="string">'aegQNi8pntiOE4R2z0e5B84D'</span>,</div><div class="line">&#125;);</div><div class="line"><span class="built_in">console</span>.log(AV);</div></pre></td></tr></table></figure>
<p>appId和appKey是LeanCloud里设置下应用Key对应的AppId和AppKey<br>打印AV无异常则环境配置OK</p>
<a id="more"></a>
<h3 id="增删改查"><a href="#增删改查" class="headerlink" title="增删改查"></a>增删改查</h3><p>在需要使用的page里添加</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="keyword">const</span> AV = <span class="built_in">require</span>(<span class="string">'../../libs/av-weapp-min.js'</span>);</div></pre></td></tr></table></figure>
<ul>
<li>增</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">// 声明一个 Todo 类型</span></div><div class="line"><span class="keyword">var</span> Todo = AV.Object.extend(<span class="string">'Todo'</span>);</div><div class="line"><span class="comment">// 新建一个 Todo 对象</span></div><div class="line"><span class="keyword">var</span> todo = <span class="keyword">new</span> Todo();</div><div class="line">todo.set(<span class="string">'title'</span>, <span class="string">'工程师周会2'</span>);</div><div class="line">todo.set(<span class="string">'content'</span>, <span class="string">'每周工程师会议，周一下午2点3'</span>);</div><div class="line">todo.save().then(<span class="function"><span class="keyword">function</span> (<span class="params">todo</span>) </span>&#123;</div><div class="line"><span class="comment">// 成功保存之后，执行其他逻辑.</span></div><div class="line"><span class="built_in">console</span>.log(<span class="string">'New object created with objectId: '</span> + todo.id);</div><div class="line">&#125;, <span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</div><div class="line"><span class="comment">// 异常处理</span></div><div class="line"><span class="built_in">console</span>.error(<span class="string">'Failed to create new object, with error message: '</span> + error.message);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<ul>
<li>删</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> todo = AV.Object.createWithoutData(<span class="string">'Todo'</span>, <span class="string">'5993ff06a22b9d0057223487'</span>);</div><div class="line">todo.destroy().then(<span class="function"><span class="keyword">function</span> (<span class="params">success</span>) </span>&#123;</div><div class="line">    <span class="comment">// 删除成功</span></div><div class="line">&#125;, <span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</div><div class="line">    <span class="comment">// 删除失败</span></div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<ul>
<li>改  </li>
</ul>
<p>第一种方法</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">// 第一个参数是 className，第二个参数是 objectId</span></div><div class="line"><span class="keyword">var</span> todo = AV.Object.createWithoutData(<span class="string">'Todo'</span>, <span class="string">'5993ff06a22b9d0057223487'</span>);</div><div class="line"><span class="comment">// 修改属性</span></div><div class="line">todo.set(<span class="string">'content'</span>, <span class="string">'每周工程师会议，本周改为周三下午3点半。'</span>);</div><div class="line"><span class="comment">// 保存到云端</span></div><div class="line">todo.save();</div></pre></td></tr></table></figure>
<p>第二种方法</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">// 执行 CQL 语句实现更新一个 TodoFolder 对象</span></div><div class="line">AV.Query.doCloudQuery(<span class="string">'update TodoFolder set name="家庭" where objectId="558e20cbe4b060308e3eb36c"'</span>)</div><div class="line">.then(<span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</div><div class="line">    <span class="comment">// data 中的 results 是本次查询返回的结果，AV.Object 实例列表</span></div><div class="line">    <span class="keyword">var</span> results = data.results;</div><div class="line">&#125;, <span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</div><div class="line">    <span class="comment">// 异常处理</span></div><div class="line">    <span class="built_in">console</span>.error(error);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<ul>
<li>查</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> query = <span class="keyword">new</span> AV.Query(<span class="string">'Todo'</span>);</div><div class="line">query.find().then(<span class="function"><span class="keyword">function</span> (<span class="params">todos</span>) </span>&#123;</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; todos.length; i++) &#123;</div><div class="line">        <span class="keyword">var</span> todo = todos[i];</div><div class="line">        <span class="comment">// 并不需要网络访问</span></div><div class="line">        <span class="keyword">var</span> id = todo.get(<span class="string">'objectId'</span>);</div><div class="line">        <span class="keyword">var</span> content = todo.get(<span class="string">'content'</span>);</div><div class="line">        <span class="built_in">console</span>.log(<span class="string">"id="</span> + id);</div><div class="line">        <span class="built_in">console</span>.log(<span class="string">"content="</span> + content);</div><div class="line">    &#125;</div><div class="line">&#125;, <span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/小程序/" rel="tag"># 小程序</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/11/小程序开发技巧/" rel="next" title="小程序开发技巧">
                <i class="fa fa-chevron-left"></i> 小程序开发技巧
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Soaic" />
          <p class="site-author-name" itemprop="name">Soaic</p>
           
              <p class="site-description motion-element" itemprop="description">Welcome!</p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#学习资料"><span class="nav-number">1.</span> <span class="nav-text">学习资料</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置环境"><span class="nav-number">2.</span> <span class="nav-text">配置环境</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#增删改查"><span class="nav-number">3.</span> <span class="nav-text">增删改查</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Soaic</span>
</div>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("nSNhFcJCeysT9vRXgfNvtbQF-gzGzoHsz", "aegQNi8pntiOE4R2z0e5B84D");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
